package com.chaoyong.higo.fragment;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.chaoyong.higo.R;
import com.chaoyong.higo.activity.ProductDetailActivity;
import com.chaoyong.higo.activity.SearchActivity;
import com.chaoyong.higo.adapter.NewsetSortAdapter;
import com.chaoyong.higo.adapter.RecomAdapter;
import com.chaoyong.higo.adapter.ShopsAdapter;
import com.chaoyong.higo.adapter.RecomAdapter.SetHoldOnClinck;
import com.chaoyong.higo.adapter.ShopsAdapter.HolderClickListener;
import com.chaoyong.higo.adapter.ShopsAdapter.HolderListener;
import com.chaoyong.higo.base.BaseFragment;
import com.chaoyong.higo.bean.ShopsBean;
import com.chaoyong.higo.bean.ShopsBean.DataEntity.ListEntity;
import com.chaoyong.higo.utils.Values;
import com.chaoyong.higo.view.BadgeView;
import com.chaoyong.higo.view.TitleView;
import com.chaoyong.higo.view.XListView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

/**
 * ������Ʒ
 * 
 * @author 丁晶
 * 
 */
public class FragAllShops extends BaseFragment implements OnClickListener {
	private TitleView fragshop_title;
	private XListView fragshop_xListView;
	private ShopsAdapter adapter;
	private LinearLayout layout, sort_lay;
	// 人气、分类筛选列表
	private ListView sort_lv, recommend_lv;
	private TextView fragshops_sort_bt, fragshops_recom_bt;
	private boolean s = true, r = true;

	private int mTouchSlop;
	private float mFirstY;
	private float mCurrentY;
	// 动画时间
	private int AnimationDuration = 1000;
	// 正在执行的动画数量
	private int number = 0;
	// 是否完成清理
	private boolean isClean = false;
	private FrameLayout animation_viewGroup;
	// 购物车旁标
	private BadgeView badgeView;
	private Handler myHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				// 用来清除动画后留下的垃圾
				try {
					animation_viewGroup.removeAllViews();
				} catch (Exception e) {

				}

				isClean = false;

				break;
			default:
				break;
			}
		}
	};
	private ShopsBean beans;
	private String high = "", low = "";
	private int num = 10;
	private RecomAdapter recomAdapter;
	private List<ListEntity> list;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.frag_all_shops, container, false);
		return mView;
	}

	@Override
	public void findView() {
		fragshop_title = (TitleView) mView.findViewById(R.id.fragshops_title);
		fragshop_xListView = (XListView) mView
				.findViewById(R.id.fragshop_xListView);
		layout = (LinearLayout) getActivity().findViewById(R.id.main_cart_lay);
		// 人气、 分类列表
		sort_lv = (ListView) mView.findViewById(R.id.sort_lv);
		recommend_lv = (ListView) mView.findViewById(R.id.recommend_lv);
		sort_lay = (LinearLayout) mView.findViewById(R.id.fragshops_sort_lay);

		fragshops_recom_bt = (TextView) mView
				.findViewById(R.id.fragshops_recom_bt);
		fragshops_sort_bt = (TextView) mView.findViewById(R.id.fragshops_sort_bt);

		fragshops_recom_bt.setOnClickListener(this);
		fragshops_sort_bt.setOnClickListener(this);
	}

	@Override
	public void init() {
		mTouchSlop = ViewConfiguration.get(mContext).getScaledTouchSlop();
		fragshop_title.setTitleText("所有商品",
				mContext.getResources().getColor(R.color.home_text));
		fragshop_title.setTitleBack(mContext.getResources().getColor(
				R.color.white));
		fragshop_title.setRightImage(R.drawable.title_search_orange);
		fragshop_title.setonRightClinck(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(mContext, SearchActivity.class));
			}
		});
		recomAdapter = new RecomAdapter(mContext);
		beans = new ShopsBean();
		list=new ArrayList<ListEntity>();
		// 网络请求
		shops();
		sort_lv.setAdapter(new NewsetSortAdapter(mContext));
		recommend_lv.setAdapter(recomAdapter);
		// 条件筛选
		recomAdapter.setOnHolderClickListener(new SetHoldOnClinck() {

			@Override
			public void onclick(int position) {
				if (position == 1) {
					high = "goods_price desc";
					low = "";
				} else if (position == 2) {
					high = "";
					low = "goods_price";
				}
				recommend_lv.setVisibility(View.GONE);
				shops();
			}
		});
		badgeView = new BadgeView(mContext, layout);
		badgeView.setBadgeMargin(30, 0);
		badgeView.setBadgeCount(1);
		animation_viewGroup = createAnimLayout();
		
//		fragshop_xListView.setPullRefresh(false);
//		fragshop_xListView.setPullLoadEnable(false);
//		fragshop_xListView.setOnTouchListener(onTouchListener);
//		fragshop_xListView.setOnTouchListener(new OnTouchListener() {
//
//			@Override
//			public boolean onTouch(View v, MotionEvent event) {
//				switch (event.getAction()) {
//				case MotionEvent.ACTION_DOWN:
////					sort_lay.setVisibility(View.VISIBLE);
////					fragshop_title.setVisibility(View.VISIBLE);
//					break;
//				case MotionEvent.ACTION_UP:
////					sort_lay.setVisibility(View.GONE);
////					fragshop_title.setVisibility(View.GONE);
//					break;
//				default:
//					break;
//				}
//				switch (event.getAction()) {
//				case MotionEvent.ACTION_DOWN:
//					mFirstY = event.getY();
//					break;
//				case MotionEvent.ACTION_MOVE:
//					mCurrentY = event.getY();
//					if (mCurrentY - mFirstY > mTouchSlop) {
//						// 下滑 显示titleBar
//						sort_lay.setVisibility(View.VISIBLE);
//						fragshop_title.setVisibility(View.VISIBLE);
//					} else if (mFirstY - mCurrentY > mTouchSlop) {
//						// 上滑 隐藏titleBar
//						sort_lay.setVisibility(View.GONE);
//						fragshop_title.setVisibility(View.GONE);
//					}
//					break;
//				case MotionEvent.ACTION_UP:
//					break;
//				}
//				return false;
//			}
//
//		});
//		fragshop_xListView.setXListViewListener(new IXListViewListener() {
//			
//			@Override
//			public void onRefresh() {
//				sort_lay.setVisibility(View.VISIBLE);
//				fragshop_title.setVisibility(View.VISIBLE);
//			}
//			
//			@Override
//			public void onLoadMore() {
//				
//			}
//		});
//		fragshop_xListView.setOnScrollListener(new OnScrollListener() {
//
//			// 这个Listener其实是用来对付当用户的手离开列表后列表仍然在滑动的情况，也就是SCROLL_STATE_FLING
//
//			int lastPosition = 0;// 上次滚动到的第一个可见元素在listview里的位置——firstVisibleItem
//			int state = SCROLL_STATE_IDLE;
//
//			@Override
//			public void onScrollStateChanged(AbsListView view, int scrollState) {
//				// 记录当前列表状态
//				state = scrollState;
//			}
//
//			@Override
//			public void onScroll(AbsListView view, int firstVisibleItem,
//					int visibleItemCount, int totalItemCount) {
//				if (firstVisibleItem >= (totalItemCount - visibleItemCount)) {
//					if (list.size()>0) {
//						num+=10;
//						list.clear();
//						shops();
//						sort_lay.setVisibility(View.VISIBLE);
//						fragshop_title.setVisibility(View.VISIBLE);
//					}
//				}
//				if (firstVisibleItem == 0) {
//					// animateBack();
//				}
//				if (firstVisibleItem > 0) {
//					if (firstVisibleItem > lastPosition
//							&& state == SCROLL_STATE_FLING) {
//						// 如果上次的位置小于当前位置，那么隐藏头尾元素
//						sort_lay.setVisibility(View.GONE);
//						fragshop_title.setVisibility(View.GONE);
//					}
//
//					// ================================
//					if (firstVisibleItem < lastPosition
//							&& state == SCROLL_STATE_FLING) {
//						// 如果上次的位置大于当前位置，那么显示头尾元素，其实本例中，这个if没用
//						// 如果是滑动ListView触发的，那么，animateBack()肯定已经执行过了，所以没有必要
//						// 如果是点击按钮啥的触发滚动，那么根据设计原则，按钮肯定是头尾元素之一，所以也不需要animateBack()
//						// 所以这个if块是不需要的
//						sort_lay.setVisibility(View.VISIBLE);
//						fragshop_title.setVisibility(View.VISIBLE);
//					}
//					// 这里没有判断(firstVisibleItem == lastPosition && state ==
//					// SCROLL_STATE_FLING)的情况，
//					// 但是如果列表中的单个item如果很长的话还是要判断的，只不过代码又要多几行
//					// 但是可以取巧一下，在触发滑动的时候拖动执行一下animateHide()或者animateBack()——本例中的话就写在那个点击事件里就可以了）
//					// BTW，如果列表的滑动纯是靠手滑动列表，而没有类似于点击一个按钮滚到某个位置的话，只要第一个if就够了…
//
//				}
//				lastPosition = firstVisibleItem;
//			}
//		});
	}

	private void shops() {
		HttpUtils http = new HttpUtils();
		RequestParams params = new RequestParams();
		JSONObject object;
		try {
			object = new JSONObject();
			object.put("path", "Home/Goods/index");
			object.put("order", high);
			object.put("order", low);
			object.put("order", "id desc");
			params.setBodyEntity(new StringEntity(object.toString(), "UTF-8"));
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		http.send(HttpMethod.POST, Values.SHOP_ALL, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						fragshop_xListView.stopLoadMore();
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						String result = arg0.result;
						if (result != null) {
							Gson gson = new GsonBuilder().create();

							beans = gson.fromJson(result,new TypeToken<ShopsBean>() {}.getType());
							if (beans.getStatus().equals("1")) {
								fragshop_xListView.stopLoadMore();
								list.addAll(beans.getData().getList());
								adapter = new ShopsAdapter(mContext, list);
								adapter.notifyDataSetChanged();
								adapter.SetOnSetHolderClickListener(new HolderClickListener() {

									@Override
									public void onHolderClick(
											Drawable drawable,
											int[] start_location) {
										// num++;
										if (badgeView.isShown()) {
											badgeView.increment(1);
										} else {
											badgeView.show();
										}
										doAnim(drawable, start_location);
									}
								});
								adapter.SetOnHolderClickListener(new HolderListener() {

									public void onSetHolderClick() {
										startActivity(new Intent(mContext,
												ProductDetailActivity.class));
									}
								});
								// fragshop_xListView.setPullRefreshEnable(false);
								fragshop_xListView.setAdapter(adapter);

							}
						}
					}
				});
	}

	View.OnTouchListener onTouchListener = new View.OnTouchListener() {

		float lastY = 0f;
		float currentY = 0f;
		// 下面两个表示滑动的方向，大于0表示向下滑动，小于0表示向上滑动，等于0表示未滑动
		int lastDirection = 0;
		int currentDirection = 0;

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				lastY = event.getY();
				currentY = event.getY();
				currentDirection = 0;
				lastDirection = 0;
				break;
			case MotionEvent.ACTION_MOVE:
				if (fragshop_xListView.getFirstVisiblePosition() > 0) {
					// 只有在listView.getFirstVisiblePosition()>0的时候才判断是否进行显隐动画。因为listView.getFirstVisiblePosition()==0时，
					// ToolBar——也就是头部元素必须是可见的，如果这时候隐藏了起来，那么占位置用了headerview就被用户发现了
					// 但是当用户将列表向下拉露出列表的headerview的时候，应该要让头尾元素再次出现才对——这个判断写在了后面onScrollListener里面……
					float tmpCurrentY = event.getY();
					if (Math.abs(tmpCurrentY - lastY) > mTouchSlop) {// 滑动距离大于touchslop时才进行判断
						currentY = tmpCurrentY;
						currentDirection = (int) (currentY - lastY);
						if (lastDirection != currentDirection) {
							// 如果与上次方向不同，则执行显/隐动画
							if (currentDirection < 0) {
								// sort_lay.setVisibility(View.VISIBLE);
								// fragshop_title.setVisibility(View.VISIBLE);
							} else {
								// sort_lay.setVisibility(View.GONE);
								// fragshop_title.setVisibility(View.GONE);
							}
						}
					}
				}
				break;
			case MotionEvent.ACTION_CANCEL:
			case MotionEvent.ACTION_UP:
				// 手指抬起的时候要把currentDirection设置为0，这样下次不管向哪拉，都与当前的不同（其实在ACTION_DOWN里写了之后这里就用不着了……）
				currentDirection = 0;
				lastDirection = 0;
				break;
			}
			return false;
		}
	};

	private void doAnim(Drawable drawable, int[] start_location) {
		if (!isClean) {
			setAnim(drawable, start_location);
		} else {
			try {
				animation_viewGroup.removeAllViews();
				isClean = false;
				setAnim(drawable, start_location);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				isClean = true;
			}
		}
	}

	/**
	 * @Description: 创建动画层
	 * @param
	 * @return void
	 * @throws
	 */
	private FrameLayout createAnimLayout() {
		// ViewGroup rootView = (ViewGroup) this.getWindow().getDecorView();
		ViewGroup rootView = (ViewGroup) getActivity().getWindow()
				.getDecorView();
		FrameLayout animLayout = new FrameLayout(mContext);
		FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
				FrameLayout.LayoutParams.MATCH_PARENT,
				FrameLayout.LayoutParams.MATCH_PARENT);
		animLayout.setLayoutParams(lp);
		animLayout.setBackgroundResource(android.R.color.transparent);
		rootView.addView(animLayout);
		return animLayout;

	}

	/**
	 * @deprecated 将要执行动画的view 添加到动画层
	 * @param vg
	 *            动画运行的层 这里是frameLayout
	 * @param view
	 *            要运行动画的View
	 * @param location
	 *            动画的起始位置
	 * @return
	 */
	private View addViewToAnimLayout(ViewGroup vg, View view, int[] location) {
		int x = location[0];
		int y = location[1];
		vg.addView(view);
		FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(dip2px(
				mContext, 90), dip2px(mContext, 90));
		lp.leftMargin = x;
		lp.topMargin = y;
		view.setPadding(5, 5, 5, 5);
		view.setLayoutParams(lp);

		return view;
	}

	/**
	 * dip，dp转化成px 用来处理不同分辨路的屏幕
	 * 
	 * @param context
	 * @param dpValue
	 * @return
	 */
	private int dip2px(Context context, float dpValue) {
		float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 动画效果设置
	 * 
	 * @param drawable
	 *            将要加入购物车的商品
	 * @param start_location
	 *            起始位置
	 */
	private void setAnim(Drawable drawable, int[] start_location) {

		Animation mScaleAnimation = new ScaleAnimation(1.5f, 0.0f, 1.5f, 0.0f,
				Animation.RELATIVE_TO_SELF, 0.1f, Animation.RELATIVE_TO_SELF,
				0.1f);
		mScaleAnimation.setDuration(AnimationDuration);
		mScaleAnimation.setFillAfter(true);

		final ImageView iview = new ImageView(mContext);
		iview.setImageDrawable(drawable);
		final View view = addViewToAnimLayout(animation_viewGroup, iview,
				start_location);
		view.setAlpha(0.6f);

		int[] end_location = new int[2];
		layout.getLocationInWindow(end_location);
		int endX = end_location[0];
		int endY = end_location[1] - start_location[1];

		Animation mTranslateAnimation = new TranslateAnimation(0, endX, 0, endY);
		Animation mRotateAnimation = new RotateAnimation(0, 180,
				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
				0.5f);
		mRotateAnimation.setDuration(AnimationDuration);
		mTranslateAnimation.setDuration(AnimationDuration);
		AnimationSet mAnimationSet = new AnimationSet(true);

		mAnimationSet.setFillAfter(true);
		mAnimationSet.addAnimation(mRotateAnimation);
		mAnimationSet.addAnimation(mScaleAnimation);
		mAnimationSet.addAnimation(mTranslateAnimation);

		mAnimationSet.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				number++;
			}

			@Override
			public void onAnimationEnd(Animation animation) {

				number--;
				if (number == 0) {
					isClean = true;
					myHandler.sendEmptyMessage(0);
				}

			}

			@Override
			public void onAnimationRepeat(Animation animation) {

			}

		});
		view.startAnimation(mAnimationSet);

	}

	/**
	 * 内存过低时及时处理动画产生的未处理冗余
	 */
	@Override
	public void onLowMemory() {
		isClean = true;
		try {
			animation_viewGroup.removeAllViews();
		} catch (Exception e) {
			e.printStackTrace();
		}
		isClean = false;
		super.onLowMemory();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.fragshops_sort_bt:
			if (s == true) {
				sort_lv.setVisibility(View.VISIBLE);
				recommend_lv.setVisibility(View.GONE);
				s = false;
			} else if (s == false) {
				sort_lv.setVisibility(View.GONE);
				s = true;
				r = true;
			}
			break;
		case R.id.fragshops_recom_bt:
			if (r == true) {
				recommend_lv.setVisibility(View.VISIBLE);
				sort_lv.setVisibility(View.GONE);
				r = false;
			} else if (r == false) {
				recommend_lv.setVisibility(View.GONE);
				r = true;
				s = true;
			}
			break;

		default:
			break;
		}
	}
}
